import json
import time
from datetime import datetime
import csv

# 读取船舶模拟数据
def read_shipdata():
    data_input = []
    mmsi_list = [
        '303981000','369970409','368913000','368765000','368870000',
        '368006000','368776000','369970669','367838000',
        '367837000','367836000','367835000','548320500','548313500',
        '548409800','548410800','548135500','548909500','548897700',
        '548229800','428000000'
        # ,'368926457'
    ]
    max_timestamp = 0
    for mmsi in mmsi_list:
        file_path = f'D:/WorkSpace/TrackRelation/ais-20250620/singleais/{mmsi}.json'
        track_data = {
            'trackId': mmsi,
            'trackData': []
        }
        with open(file_path, 'r', encoding='utf-8') as file:
            data_json = json.load(file)
            for item in data_json:
                datetime_obj = datetime.strptime(item['ti'], '%Y-%m-%d %H:%M:%S')
                item_timestamp = datetime_obj.timestamp()
                track_data['trackData'].append({
                    'timestamp': item_timestamp,
                    'longitude': round(float(item['lo']) / 60, 4),
                    'latitude': round(float(item['la']) / 60, 4),
                    'altitude': 0,
                    'speed': float(item['sp'])
                })
                if item_timestamp > max_timestamp:
                    max_timestamp = item_timestamp
        data_input.append(track_data)
    return data_input, max_timestamp

# 读取船舶模拟数据
def read_shipdata2(starttime, endtime):
    data_input = []
    mmsi_list = [
        '303981000','369970409','368913000','368765000','368870000',
        '368006000','368776000','369970669','367838000',
        '367837000','367836000','367835000','548320500','548313500',
        '548409800','548410800','548135500','548909500','548897700',
        '548229800','428000000'
        # ,'368926457'
    ]
    max_timestamp = 0
    for mmsi in mmsi_list:
        file_path = f'D:/WorkSpace/TrackRelation/ais-20250620/singleais/{mmsi}.json'
        track_data = {
            'trackId': mmsi,
            'trackData': []
        }
        with open(file_path, 'r', encoding='utf-8') as file:
            data_json = json.load(file)
            for item in data_json:
                datetime_obj = datetime.strptime(item['ti'], '%Y-%m-%d %H:%M:%S')
                item_timestamp = datetime_obj.timestamp()
                if item_timestamp >= starttime and item_timestamp <= endtime:
                    track_data['trackData'].append({
                        'timestamp': item_timestamp,
                        'longitude': round(float(item['lo']) / 60, 4),
                        'latitude': round(float(item['la']) / 60, 4),
                        'altitude': 0,
                        'speed': float(item['sp'])
                    })
                    if item_timestamp > max_timestamp:
                        max_timestamp = item_timestamp
        if len(track_data['trackData']) > 0:
            data_input.append(track_data)
    return data_input, max_timestamp

# 读取飞机模拟数据
def read_planedata():
    data_input = []
    track_data = {}
    file_path_list = [
        './data/1748623163.json',
        './data/1748623212.json',
        './data/1748623281.json',
        './data/1748623337.json'
    ]
    for file_path in file_path_list:
        with open(file_path, 'r', encoding='utf-8') as file:
            data_json = json.load(file)
            timestamp = float(data_json['time'])
            for item in data_json['states']:
                track_id = item[0]
                if track_data.get(track_id, None) is None:
                    track_data[track_id] = {
                        'trackId': track_id,
                        'trackData': []
                    }
                
                speed_str = item[9]
                speed = 0.0
                try:
                    if speed_str:
                        speed = float(speed_str)
                except (ValueError, TypeError):
                    speed = 0.0

                altitude_str = item[13]
                track_data[track_id]['trackData'].append({
                    'timestamp': timestamp,
                    'longitude': round(float(item[5]), 6),
                    'latitude': round(float(item[6]), 6),
                    'altitude': float(altitude_str) if altitude_str is not None and altitude_str.isnumeric() else 0,
                    'speed': speed,
                    'on_ground': altitude_str == 'ground'
                })
    for track_item in track_data.values():
        data_input.append(track_item)
    return data_input, 1748623337

# 读取重要区域和港口的位置信息
def read_areadata():
    file_path = './data/importPlace_port.json'
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except FileNotFoundError:
        raise FileNotFoundError(f"文件 {file_path} 不存在")
    except json.JSONDecodeError:
        raise ValueError(f"文件 {file_path} 不是有效的JSON格式")

    area_idx = 1
    area_list = []
    # 处理港口数据 (placeType = 'port')
    for port in data.get('interestPorts', []):
        # 确保areaPos包含4个值
        area_pos = port.get('areaPos')
        if area_pos and len(area_pos) == 4:
            area_list.append({
                'area_id': port.get('regionName', area_idx),
                'area_type': 'port',
                'coords_bbox': [float(d) for d in area_pos]
            })
            area_idx += 1

    # 处理重要区域数据 (placeType = 'impArea')
    for area in data.get('ImportArea', []):
        # 确保areaPos包含4个值
        area_pos = area.get('areaPos')
        if area_pos and len(area_pos) == 4:
            area_list.append({
                'area_id': area.get('regionName', area_idx),
                'area_type': 'impArea',
                'coords_bbox': [float(d) for d in area_pos]
            })
            area_idx += 1
    return area_list

# 读取重要区域和港口的位置信息
def read_areadata2():
    file_path = './data/track_area.csv'
    area_list = []
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            reader = csv.reader(f)
            next(reader)
            for row in reader:
                if row[2] == 'port':
                    bbox_arr = row[4].split(',')
                    area_list.append({
                        'area_id': row[0],
                        'area_type': 'port',
                        'coords_bbox': [float(d) for d in bbox_arr]
                    })
                elif row[2] == 'area':
                    bbox_arr = row[4].split(',')
                    area_list.append({
                        'area_id': row[0],
                        'area_type': 'impArea',
                        'coords_bbox': [float(d) for d in bbox_arr]
                    })
    except FileNotFoundError:
        raise FileNotFoundError(f"文件 {file_path} 不存在")
    except json.JSONDecodeError:
        raise ValueError(f"文件 {file_path} 不是有效的JSON格式")
    return area_list

def write_actiondata(action_list, is_ship):
    ret_path = './data/track_action.csv'
    ret_keys = ['target_id','target_type','action_code','start_time','end_time','area_id','properties']
    with open(ret_path, 'a', encoding='utf-8') as file:
        if file.tell() == 0:
            csv_head = ','.join(ret_keys) + '\n'
            file.write(csv_head)
        for item in action_list:
            date_start = datetime.fromtimestamp(item['startTime'])
            date_end = datetime.fromtimestamp(item['endTime'])
            csv_row = [item['trackId'],'S' if is_ship else 'P',item['actionKey'], date_start.strftime('%Y-%m-%d %H:%M:%S'), date_end.strftime('%Y-%m-%d %H:%M:%S'), item.get('areaId',''), item.get('properties','')]
            csv_line = ','.join(map(str, csv_row)) + '\n'
            file.write(csv_line)

if __name__ == '__main__':    
    # # 读取文件生成飞机实时状态类输入数据
    # plane_list, now_timestamp = read_planedata()
    # print(f'read_planedata: {len(plane_list)},{now_timestamp}')
    # print(f'read_planedata[0]: {plane_list[0]}')
    # # 读取文件生成时序轨迹类输入数据
    # ship_list, now_timestamp = read_shipdata()
    # print(f'read_shipdata: {len(ship_list)},{now_timestamp}')
    # print(f'read_shipdata[0].trackData[0]: {ship_list[0]["trackData"][0]}')
    # 读取重要区域数据
    area_list = read_areadata()
    print(f'read_areadata: {area_list}')
    # 读取重要区域数据
    area_list2 = read_areadata2()
    print(f'read_areadata2: {area_list2}')
    # 分时间段调用
    # # 读取文件生成时序轨迹类输入数据
    # timestr_list = [
    #     '2025-01-01 00:00:00',
    #     '2025-02-01 00:00:00',
    #     '2025-03-01 00:00:00',
    #     '2025-04-01 00:00:00',
    #     '2025-05-01 00:00:00',
    #     '2025-06-01 00:00:00',
    #     '2025-07-01 00:00:00'
    # ]
    # prev_timestamp = 0
    # for timestr in timestr_list:
    #     timestamp = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S').timestamp()
    #     # 读取文件数据并执行算法
    #     ship_list, now_timestamp = read_shipdata2(prev_timestamp, timestamp)
    #     print(f'read_shipdata2: {len(ship_list)}')
    #     print(f'read_shipdata2[0].trackData[0]: {ship_list[0]["trackData"][0]}')
    #     prev_timestamp = timestamp
    #     time.sleep(1)
